import datetime

from flask import current_app
from werkzeug.security import generate_password_hash

from app import manager, db
from app.models import User


@manager.option("-n", "-name", dest="name")  # @manager.option 自动注册
@manager.option("-p", "-password", dest="password")
def create_super_user(name, password):
    """创建超级管理员账户"""
    if not all([name, password]):
        current_app.logger.error("超级管理员用户名和密码不能为空")
        print("超级管理员用户名和密码不能为空")
    user = User()
    user.username = name
    user.password_hash = generate_password_hash(password)
    user.email_address = "admin@ztccloud.com.cn"
    user.last_seen = datetime.datetime.now()

    try:
        db.session.add(user)
    except Exception as e:
        current_app.logger.error(e)
        print(f"添加管理员账户失败，name={name}，password={password}")
    else:
        db.session.commit()

    current_app.logger.info(f"添加管理员账户成功，name={name}，password={password}")
    print(f"添加管理员账户成功，name={name}，password={password}")


if __name__ == '__main__':
    manager.run()
